##### Uncertainty test in R #####

rm(list=ls())
set.seed(23789)

#set working directory
setwd("C:/Users/Admin/Dropbox/Personalism Project/_beforeAR/BJPS/Uncertainty")

need.to.install<-FALSE
if(need.to.install){
  install.packages("car")
  install.packages("plyr")
  install.packages("lattice")
}

library(car)
library(foreign)
library(plyr)
library(lattice)

simnum<-1000
names<-matrix(, nrow = 1, ncol = simnum+2)				# to store column names
names[1,1]<-"cowcode"
names[1,2]<-"year"
data.song<-read.dta("Nonstdpers.dta")    # correctly input the data set from .dta  
data.pers <- data.song[c(1:2,3:4)] 
nrdf<-nrow(data.pers)
max<-(ncol(data.pers)-2)/2							# number of latent measures: 1 in this application

for(j in 1:max){
  q<-j
  n<-matrix(, nrow = nrdf, ncol = simnum+2)
  n[,1]<-data.pers[,1] 							# cowcode
  n[,2]<-data.pers[,2]							# year
  for(i in 1:simnum){
    if(q==1) {
      n[,i+2]<-rnorm(1:nrow(data.pers), mean= data.pers$latentmean, sd=data.pers$latentse)
    }	
    d<-i
    toString(d)
    x <- c("sim", d)
    x<-paste(x, collapse="")
    names[1,i+2]<-x											# add column names by i
  }
  dimnames(n)<-list(c(), c(names))
  if(q==1) {
    n<-write.csv(n,"sim1000.csv")
  }
}